#include "StdAfx.h"
#include "VSqlTable.h"

// VSqlTable //////////////////////////////////////////////////////////////////

//
bool VSqlTable::createOrReplace
(
	const QSqlDatabase &db,
	VSqlMeta &parent,
	VSqlItem &itemTable,
	VSqlItemList &itemFields
)
{
	VSqlNode node;
	VSqlNode_select_byAnd selNode(
		db,
		node.fields(),
		VSqlFieldPtrList() << &node.idNodeParent << &node.refIdItem
	);
	VSqlNode_insert insNode(db);

	VSqlItem item;
	VSqlItem_select_byAnd selTable(
		db,
		VSqlFieldPtrList() << &item.idItem,
		VSqlFieldPtrList() << &item.keyName << &item.itemType
	);
	VSqlItem_select_byAnd selItem(
		db,
		item.fields(),
		VSqlFieldPtrList() << &item.keyName << &item.itemType
	);
	VSqlItem_insert insItem(db);

	selItem.exec(VSqlFieldPtrList() << &itemTable.keyName << &itemTable.itemType);
	if (!selItem.next(itemTable.fields()))
		insItem.exec(itemTable);

	VSqlNode nodeTable;
		nodeTable.idNodeParent.setValue(parent.node().idNode.value());
		nodeTable.refIdItem	  .setValue(itemTable.idItem.value());
	
	selNode.exec(VSqlFieldPtrList() << &nodeTable.idNodeParent << &nodeTable.refIdItem);
	if (!selNode.next(nodeTable.fields()))
	{
		nodeTable.idNode.clear();
		insNode.exec(nodeTable);
	}

	foreach (VSqlItem itemField,itemFields)
	{
		selItem.exec(VSqlFieldPtrList() << &itemField.keyName << &itemField.itemType);
		if (!selItem.next(itemField.fields()))
		{
			if (itemField.isRef())
			{
				item.keyName .setValue(itemField.tmpRefKeyName());
				item.itemType.setValue(ESqlItemType_table);

				selTable.exec(VSqlFieldPtrList() << &item.keyName << &item.itemType);
				if (!selTable.next(VSqlFieldPtrList() << &item.idItem))
					return false;

				itemField.refIdItem.setValue(item.idItem.value());
			}

			itemField.idItemParent.setValue(itemTable.idItem.value());
			insItem.exec(itemField);
		}
		
		VSqlNode nodeField;
			nodeField.idNodeParent.setValue(nodeTable.idNode.value());
			nodeField.refIdItem	  .setValue(itemField.idItem.value());

		selNode.exec(VSqlFieldPtrList() << &nodeField.idNodeParent << &nodeField.refIdItem);
		if (!selNode.next(nodeField.fields()))
		{
			nodeField.idNode.clear();
			insNode.exec(nodeField);
		}

//QString ss; itemField.sqlDbFieldNameAndType(ss);
//ss=ss;
	}

	return true;
}
